package com.example.pulllistview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/9/30 0030.
 */

public class RefeshListView extends ListView {
    private TextView headr_tv_time, tv_status_header;
    private ImageView iv_header;
    private ProgressBar pb_header;
    private static final String TAG = "RefeshListView";
    private int downy, height, offHeitht;
    private View view;
    private final int down_pull = 0;
    private final int down_up = 1;
    private final int down_fresh = 2;
    private int current = down_pull;
    private RotateAnimation up, down;
    private OnRefreshListener mrefresh;

    public RefeshListView(Context context) {
        super(context);
        initHeader();
    }

    private void initHeader() {
        view = View.inflate(getContext(), R.layout.listview_header, null);
        iv_header = (ImageView) view.findViewById(R.id.iv_header);
        pb_header = (ProgressBar) view.findViewById(R.id.pb_header);
        headr_tv_time = (TextView) view.findViewById(R.id.headr_tv_time);
        tv_status_header = (TextView) view.findViewById(R.id.tv_status_header);
        headr_tv_time.setText("最后刷新时间："+getCurrentTime());
//        int height=-view.getHeight();//此方法在控件没有显示到屏幕上面之前一直获取都是0
        //测量头布局
        view.measure(0, 0);//给0，是让系统框架给我们测量头布局宽高，相当于measure已经执行，不然下面得到的值仍然是0.
        //隐藏头布局
        height = -view.getMeasuredHeight();//测量之后就能得到值，meassure之后。
        view.setPadding(0, height, 0, 0);
        this.addHeaderView(view);
        initAnimation();
    }

    /**
     * 初始化箭头动画
     */
    private void initAnimation() {
        up = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        up.setDuration(500);
        up.setFillAfter(true);//停止在最后的状态
        down = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        down.setDuration(500);
        down.setFillAfter(true);//停止在最后的状态
    }

    public RefeshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initHeader();
    }

    public RefeshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downy = (int) ev.getY();

                break;
            case MotionEvent.ACTION_MOVE:
                //判断当前状态是否在正在刷新.防止正在刷新还可以下拉
                if (current == down_fresh) {
                    break;
                }
                int movey = (int) ev.getY();
                int offsety = movey - downy;//移动间距
                //重新计算头布局高度
                offHeitht = height + offsety;
                //如果top值小于头高度，不进行滑动操作
                //并且第一个条目是0时候才能滑动
                int n = getFirstVisiblePosition();//获得当前显示的第一个position的索引。
                if (offHeitht > height && n == 0) {
                    if (offHeitht > 0 && current == down_pull) {//头布局完全显示，进入松开刷新状态
                        current = down_up;
                        freshCurrent();
                    } else if (offHeitht < 0 && current == down_up) {
                        current = down_pull;
                        freshCurrent();
                    }
                    view.setPadding(0, offHeitht, 0, 0);
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (current == down_pull) {//下拉刷新状态，如果松开，什么也不做，直接隐藏头布局
                    view.setPadding(0, height, 0, 0);
                } else if (current == down_up) {//状态是释放刷新
                    view.setPadding(0, 0, 0, 0);
                    current = down_fresh;
                    freshCurrent();
                    //调用用户的监听事件
                    if (mrefresh != null) {
                        mrefresh.onPullRefresh();
                    }
                }
                break;
            default:
                break;
        }
        return super.onTouchEvent(ev);//注意此处千万不能返回true，不然listview无法滑动。
    }

    /**
     * 根据当前状态，刷新头布局状态
     */
    private void freshCurrent() {
        switch (current) {
            case 0://下拉刷新
                tv_status_header.setText("下拉刷新");
                iv_header.startAnimation(down);//注意此处是startAnimation,而不是setAnimation
                break;
            case 1://松开刷新
                tv_status_header.setText("松开刷新");
                iv_header.startAnimation(up);
                break;
            case 2://正在刷新
                tv_status_header.setText("正在刷新...");
                iv_header.clearAnimation();//把自身动画清除掉
                iv_header.setVisibility(INVISIBLE);
                pb_header.setVisibility(VISIBLE);
                break;
        }

    }

    /**
     * 提供给使用者设置刷新的监听事件
     */
    public void setOnRefreshOnlistener(OnRefreshListener refresh) {
        this.mrefresh=refresh;
    }

    /**
     * 当listview刷新时的监听事件
     */
    public interface OnRefreshListener {
        public void onPullRefresh();
    }

    /**
     * 刷新完成，包括隐藏头布局
     */
    public void onRefreshFinish() {
        view.setPadding(0,height,0,0);
        current=down_pull;
        pb_header.setVisibility(INVISIBLE);
        iv_header.setVisibility(VISIBLE);
        tv_status_header.setText("下拉刷新");
        headr_tv_time.setText("最后刷新时间："+getCurrentTime());
    }

    /**
     * 获取最后刷新时间,按照正则表达式格式化
     */
    private String getCurrentTime() {
        SimpleDateFormat data=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return data.format(new Date());//直接new Date()即可得到当前时间
    }
}
